import React, { Component } from 'react'
import { Upload, Modal, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import {nanoid} from 'nanoid'

import {reqDeleteImg} from '../../../api'
import {BASE_IMG_URL} from '../../../utils/constants'

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

export default class PicturesWall extends Component {

    constructor (props) {
      super(props)
      let fileList = []
      // 如果传入了image
      const {image} = this.props
      if (image !== "") {
        fileList[0] = {
             uid: nanoid(),
             name: image,
             status: 'done',
             url: BASE_IMG_URL + image
           }
        // fileList = imgs.map((item, index) => ({
        //   uid: -index,
        //   name: item,
        //   status: 'done',
        //   url: BASE_IMG_URL + item
        // }))
      }

      // 初始化状态
      this.state = {
        previewVisible: false,
        previewImage: '', // 大图的url地址
        fileList: fileList,
        }
    }
    
    // 父组件调用获取fileList
    getImgs = () => {
      return this.state.fileList.map(file => file.name)
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }

        this.setState({
          previewImage: file.url || file.preview,
          previewVisible: true,
        })
      }

    handleChange = async ({file, fileList}) => {
      if (file.status === 'done') {
        const result = file.response
        if (result.status === 0) {
          message.success('图片上传成功')
          const {name, url} = result.data
          file = fileList[fileList.length - 1]
          file.name = name
          file.url = url
        } else {
          message.error(result.message)
        }
      } else if (file.status === 'removed') { // 删除
        const reponse = await reqDeleteImg(file.name)
        if (reponse.data.status === 0) {
          message.success('图片删除成功')
        } else {
          message.error('图片删除失败')
        }
      }

      this.setState({ fileList })
    }

    render() {

        const { previewVisible, previewImage, fileList } = this.state
        const uploadButton = (
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
          </div>
        )

        return (
            <div>
                <Upload
                    action="http://localhost:5000/manage/img/upload" // 上传图片的地址
                    accept="image/*" // 指定只接受图片
                    listType="picture-card"
                    name="image" // 请求参数名
                    fileList={fileList} // 已上传图片的数组
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}>
                    {fileList.length > 0 ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible} // 标识是否显示预览
                    footer={null}
                    onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' , height: '100%'}} src={previewImage} />
                </Modal>
            </div>
        )
    }
}
